package com.qk.management.controller;

import com.qk.common.PageResult;
import com.qk.common.Result;
import com.qk.entity.Dept;
import com.qk.management.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 *
 * @author MrZhao
 * @created 2025-09-29 10:31
 * @description 部门管理控制层
 *
 */
@Slf4j
@RestController
@RequestMapping("/depts")
@SuppressWarnings("all")
public class DeptController {

    @Autowired
    private DeptService deptService;

    @GetMapping("/list")
    public Result list(){
        return Result.success(deptService.list());
    }


    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id) {
        // TODO演示异常处理器使用
        //   int i=1/0;
        log.info("删除部门id:{}", id);
        deptService.deleteById(id);
        return Result.success();
    }

    /**
     * 修改部门
     *
     * @param dept
     * @return Result
     */
    @PutMapping
    public Result update(@RequestBody Dept dept) {
        log.info("修改部门:{}", dept);
        deptService.update(dept);
        return Result.success();
    }


    /**
     * 根据id查询部门
     *
     * @param id
     * @return Result
     * @PathVariable("id") 作用从路径变量/depts/{id} 中获取名字叫id路径变量值赋值给 方法的形参
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable("id") Integer id) {
        log.info("查询部门id:{}", id);
        Dept dept = deptService.getById(id);
        return Result.success(dept);
    }


    @GetMapping
    public Result page(
            @RequestParam(name = "name", required = false) String name,
            @RequestParam(name = "status", required = false) Integer status,
            @RequestParam(name = "page", defaultValue = "1") Integer page,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        PageResult<Dept> pageResult = deptService.page(name, status, page, pageSize);
        log.info("分页查询部门,参数:部门名称={},部门状态={},当前页码={},每页大小={}", name, status, page, pageSize);
        log.info("-----------------------++++++部门列表方法+++++--------------------------");
        return Result.success(pageResult);
    }


    /**
     * 新增部门
     *
     * @param dept 请求参数
     * @return Result
     */
    @PostMapping
    public Result addDept(@RequestBody Dept dept) {
        try {
            log.info("新增部门:{}", dept);
            deptService.addDept(dept);
            return Result.success();
        } catch (Exception e) {
            log.error("新增部门失败:{}", e.getMessage());
            return Result.error("新增部门失败");
        }

    }


}
